const sql = require('mssql')
const config = require('./config')

const pools = {}

// 初始化所有数据库连接
const initializePools = async () => {
  try {
    // 同时创建两个数据库的连接池
    await Promise.all([
      createPool('mesdb'),
      createPool('dcdb')
    ]);
    console.log('所有数据库连接初始化成功');
    return true;
  } catch (err) {
    console.error('数据库连接初始化失败:', err);
    throw err;
  }
};

const createPool = async (dbName) => {
  try {
    if (!pools[dbName]) {
      pools[dbName] = await sql.connect(config[dbName]);
      console.log(`Connected to database: ${dbName}`);
      
      // 添加错误处理
      pools[dbName].on('error', async err => {
        console.error(`Database ${dbName} connection error:`, err);
        delete pools[dbName];
        // 尝试重新连接
        await createPool(dbName);
      });
    }
    return pools[dbName];
  } catch (err) {
    console.error(`Error connecting to database ${dbName}:`, err);
    throw err;
  }
};

const getPool = async (dbName) => {
  if (!pools[dbName]) {
    await createPool(dbName);
  }
  return pools[dbName];
};

const getDbStatus = (dbName) => {
  return pools[dbName] ? 'connected' : 'disconnected';
};

// 关闭所有连接
const closeAllPools = async () => {
  try {
    await Promise.all(
      Object.values(pools).map(pool => pool.close())
    );
    pools = {};
    console.log('所有数据库连接已关闭');
  } catch (err) {
    console.error('关闭数据库连接时出错:', err);
    throw err;
  }
};

module.exports = {
  initializePools,
  createPool,
  getPool,
  getDbStatus,
  closeAllPools
};